import { defaultThemeType } from '@/data/index.js'
import { toRaw } from 'vue'
import { useBroadcastChannel } from '@vueuse/core'

/**
 * @Author: 宋计民
 * @Date: 2022/11/3
 * @Version: 1.0
 * @Content: 获取设置主题颜色
 */

const customEvent = new CustomEvent('primaryChange', { detail: getThemeData })
const { isSupported, channel, post, close, error, isClosed } =
  useBroadcastChannel({ name: 'primaryChange' })

export const themeKey = 'theme'

export function getPrimaryColorVal() {
  return document.documentElement.getPropertyValue('--primary-color-val')
}

/**
 * 获取主题颜色
 * @param alpha
 * @returns {string}
 */
export function getPrimaryColor(alpha = 1): string {
  const color = getComputedStyle(document.documentElement).getPropertyValue(
    '--primary-color-val'
  )
  return `rgba(${color},${alpha})`
}

/**
 * 设置主题颜色
 * @param color
 */
export function setPrimaryColor(color: string): void {
  document.documentElement.style.setProperty('--primary-color-val', color)
  document.dispatchEvent(customEvent)
}

export function setThemeColor(key: string, value: string) {
  document.documentElement.style.setProperty(key, value)
}

interface ColorObj {
  colorValue: any
}

export function setThemeValue(obj: ColorObj) {
  const color = obj.colorValue
  for (const key in color) {
    setThemeColor(key, color[key])
  }
}

/**
 * 设置主题调用的方法
 * @param obj
 */
export function setThemeValueWithEvent(obj: ColorObj) {
  setThemeValue(obj)
  localStorage.setItem(themeKey, JSON.stringify(obj))
  document.dispatchEvent(customEvent)
  post(toRaw(obj))
}

export function getThemeData() {
  const theme = localStorage.getItem(themeKey)
  if (theme) {
    return JSON.parse(theme)
  }
  return defaultThemeType
}
